#region Using

using System;
using System.Collections.Generic;
using System.Data;

using Gizmox.WebGUI.Forms;
using System.Collections;
using Gizmox.WebGUI.Common.Resources;
using System.IO;
using FlexCel.Core;
using System.Text.RegularExpressions;
using TVC.Modules.Rep;
using Gizmox.WebGUI.Common.Gateways;

#endregion

namespace TVC.Modules.Ddb
{
    public partial class DDB : ModuleParent, IHostedApplication
    {
        MyGadget mygadget;
        int _iCurrent;
        int idAllowEditLanguage = 1;
        int idAddNew = 5;
        int idEdit = 6;
        int idDelete = 7;
        int idTransferIn = 8;
        int idTransferOut = 9;
        int idConfig = 10;
        int idPrint = 11;
        int idImportData = 12;



        public DDB()
        {
            InitializeComponent();
            myHtmlbox1.OnFireEvent += DDB_OnFireEvent;
            _strType = "DDB";
        }
        private BaseForm GetBaseForm()
        {
            return GetMainForm() as BaseForm;
        }
        void DDB_OnFireEvent(string command, string args)
        {
            ThrowMsg("");
            if (command == "ANALYSERUI")
            {
                frmQDAddinDrilldown frmaddin = new frmQDAddinDrilldown("A1", MainForm.Base64ToString(args.Replace("tag=", "")), MainForm.AppConnectString);
                //frmaddin.Config = frmMain._gui.Config;
                frmaddin.BringToFront();
                frmaddin.Show();
            }
            else if (command == "DDB")
            {
                string id = GetValue(args, "id", @"[0-9]+");
                if (id != "")
                {
                    if (!GetMainForm().IsContainsTables(_strType))
                        GetMainForm().LoadDataTable(_strType);
                    using (DataTable dt = GetMainForm().GetTable(_strType))
                    {
                        foreach (DataRow row in dt.Rows)
                        {
                            if (row[DTO.LIST_GADGETInfo.Field.ID.ToString()].ToString() == id)
                            {
                                DTO.LIST_GADGETInfo infGadgte = new DTO.LIST_GADGETInfo(row);
                                _iCurrent = dt.Rows.IndexOf(row);
                                mygadget.Info = infGadgte;
                                mygadget.Reload();
                                LoadDB(args);
                                ThrowMsg(mygadget.sErr);
                                break;
                            }
                        }
                    }

                }
                else
                {
                    MainForm main = GetMainForm();

                    main.SelectCategory(command, args);
                }
            }
            else if (command == "CMD")
            {
                Dictionary<string, object> dic = new Dictionary<string, object>();
                string[] arrParam = args.Split('&');
                if (arrParam != null)
                    foreach (string it in arrParam)
                    {
                        string[] value = it.Split('=');
                        if (value != null)
                        {
                            if (value.Length == 2)
                            {
                                dic.Add(value[0], value[1]);
                            }
                        }
                    }
                if (dic.ContainsKey("window") && dic["window"].ToString() == "1")
                {
                    Forms.frmCommand frm = new Forms.frmCommand(GetMainForm());

                    frm.InitCommand(dic);
                    frm.FormClosed += (form, frmArgs) =>
                    {
                        if (((Forms.frmCommand)form).DialogResult == DialogResult.OK)
                        {
                            if (args.Contains("refresh=1"))
                            {
                                mygadget.Xls = null;
                                mygadget.XlsPrint = null;
                                LoadDB("");
                                ThrowMsg(mygadget.sErr);
                            }
                        }
                    };
                    frm.ShowDialog();

                }
                else
                {
                    if (dic.ContainsKey("id"))
                    {
                        BUS.LIST_CMDControl cmdCtr = new BUS.LIST_CMDControl();
                        DTO.LIST_CMDInfo cmdInf = cmdCtr.Get(GetMainForm().DB, dic["id"].ToString(), ref sErr);
                        try
                        {

                            Forms.frmCommand.RunCommand(this, dic, cmdInf);
                        }
                        finally
                        {

                        }

                        if (args.Contains("refresh=1"))
                        {
                            mygadget.Xls = null;
                            mygadget.XlsPrint = null;
                            LoadDB("");
                            ThrowMsg(mygadget.sErr);
                        }
                    }
                }

            }
            else if (Regex.IsMatch(command, @"P[1-9]{1}") || command == "P10")
            {
                if (args.Contains("input="))
                {
                    frmInputData frm = new frmInputData();

                    string adefault = GetValue(args, "default", @".+");
                    frm.Default = adefault;
                    frm.FormClosed += (form, frmArgs) =>
                    {
                        if (((frmInputData)form).DialogResult == DialogResult.OK)
                        {
                            mygadget.Xls = null;
                            mygadget.XlsPrint = null;
                            LoadDB(String.Format("{0}={1}", command, ((frmInputData)form).valuereturn));
                            ThrowMsg(mygadget.sErr);
                        }
                        //else
                        //{
                        //    mygadget.Xls = null;
                        //    mygadget.XlsPrint = null;
                        //    LoadDB(String.Format("{0}={1}", command, adefault));
                        //    ThrowMsg(mygadget.sErr);
                        //}
                    };
                    frm.ShowDialog();

                }
                else if (args.Contains("lookup="))
                {
                    string cate = GetValue(args, "lookup", @".+");
                    if (cate != "")
                    {
                        if (cate == "Calendar")
                        {
                            string adefault = GetValue(args, "default", @".+");
                            Forms.frmCalendar frmCal = new Forms.frmCalendar();
                            frmCal.FormClosed += (form, frmArgs) =>
                            {
                                if (((Forms.frmCalendar)form).DialogResult == DialogResult.OK)
                                {
                                    mygadget.Xls = null;
                                    mygadget.XlsPrint = null;
                                    LoadDB(String.Format("{0}={1}", command, ((Forms.frmCalendar)form).ReturnValue.ToString("yyyy-MM-dd")));
                                    ThrowMsg(mygadget.sErr);
                                }
                                else
                                {
                                    mygadget.Xls = null;
                                    mygadget.XlsPrint = null;
                                    LoadDB(String.Format("{0}={1}", command, adefault));
                                    ThrowMsg(mygadget.sErr);
                                }
                            };
                            frmCal.ShowDialog();
                        }
                        else
                        {
                            string adefault = GetValue(args, "default", @".+");
                            Forms.frmView frm = new Forms.frmView(cate, GetMainForm());
                            frm.SetParams(args);
                            frm.FormClosed += (form, frmArgs) =>
                            {
                                if (((Forms.frmView)form).DialogResult == DialogResult.OK)
                                {
                                    mygadget.Xls = null;
                                    mygadget.XlsPrint = null;
                                    DataRow row = ((Forms.frmView)form).ReturnValue;
                                    if (row.Table.PrimaryKey != null && row.Table.PrimaryKey.Length > 0)
                                        LoadDB(String.Format("{0}={1}", command, row[row.Table.PrimaryKey[0]]));
                                    else LoadDB(String.Format("{0}={1}", command, row[1]));
                                    ThrowMsg(mygadget.sErr);
                                }
                                else
                                {
                                    mygadget.Xls = null;
                                    mygadget.XlsPrint = null;
                                    LoadDB(String.Format("{0}={1}", command, adefault));
                                    ThrowMsg(mygadget.sErr);
                                }
                            };
                            frm.ShowDialog();
                        }
                    }
                }
            }
            else if (command == "SI")
            {
                string[] arr = args.Split('&');
                var cate = "";
                foreach (string tmp in arr)
                {
                    if (tmp.Contains("src="))
                    {
                        cate = tmp.Replace("src=", "");
                        break;
                    }
                }
                Forms.frmTransferIn frmTI = new Forms.frmTransferIn(cate, GetMainForm());

                frmTI.FormClosed += (form, frmArgs) =>
                {
                    if (args.Contains("refresh=1"))
                    {
                        mygadget.Xls = null;
                        mygadget.XlsPrint = null;
                        LoadDB("");
                        ThrowMsg(mygadget.sErr);
                    }
                };
                frmTI.ShowDialog();


            }
            else if (command == "MI")
            {
                string[] arr = args.Split('&');
                Forms.frmMulticlsTransferIn frmTI = new Forms.frmMulticlsTransferIn(args, GetMainForm());

                frmTI.FormClosed += (form, frmArgs) =>
                {
                    if (args.Contains("refresh=1"))
                    {
                        mygadget.Xls = null;
                        mygadget.XlsPrint = null;
                        LoadDB("");
                        ThrowMsg(mygadget.sErr);
                    }
                };
                frmTI.ShowDialog();

            }
            else
            {
                if (args.Contains("window=1"))
                {
                    BaseForm baseForm = GetBaseForm();

                    NavigationTabs tabs = null;
                    if (baseForm != null)
                        tabs = baseForm.TabsMain;
                    Forms.frmMain frm = new Forms.frmMain(command, GetMainForm()) { TabsMains = tabs };

                    frm.FormClosed += (form, frmArgs) =>
                    {
                        if (((Forms.frmMain)form).DialogResult == DialogResult.OK)
                        {
                            if (args.Contains("refresh=1"))
                            {
                                mygadget.Xls = null;
                                mygadget.XlsPrint = null;
                                LoadDB("");
                                ThrowMsg(mygadget.sErr);
                            }
                        }
                    };
                    frm.ShowDialog();


                }
                else
                {
                    MainForm main = GetMainForm();

                    main.SelectCategory(command, args);

                }
            }
        }

        private static string GetValue(string args, string param, string partern)
        {
            string id = "";
            Match mat = Regex.Match(args, String.Format(@"{0}={1}&", param, partern));

            if (mat == null || mat.Value == "")
            {
                mat = Regex.Match(args, String.Format(@"{0}={1}", param, partern));
                id = mat.Value.Replace(param + "=", "");
            }
            else id = mat.Value.Replace(param + "=", "").Replace("&", "");
            return id.Replace(param + "=", "");
        }


        #region IHostedApplication Members

        public void InitializeApplication()
        {
        }
        public string GetTitle()
        {
            return _title;
        }
        public void addRecord()
        {

        }
        public void SetObject(object obj)
        {
            string args = obj as String;
            if (args != null && args != "")
            {
                string id = GetValue(args, "id", "[0-9]+");

                if (id != "")
                {
                    if (!GetMainForm().IsContainsTables(_strType))
                        GetMainForm().LoadDataTable(_strType);
                    using (DataTable dt = GetMainForm().GetTable(_strType))
                    {
                        foreach (DataRow row in dt.Rows)
                        {
                            if (row[DTO.LIST_GADGETInfo.Field.ID.ToString()].ToString() == id)
                            {
                                DTO.LIST_GADGETInfo infGadgte = new DTO.LIST_GADGETInfo(row);
                                _iCurrent = dt.Rows.IndexOf(row);
                                mygadget.Info = infGadgte;
                                mygadget.Reload();
                                LoadDB(args);
                                ThrowMsg(mygadget.sErr);
                                break;
                            }
                        }
                    }

                }
            }
        }
        public HostedToolBarElement[] GetToolBarElements()
        {
            ArrayList objElements = new ArrayList();
            objElements.Add(new HostedToolBarButton("Previous", new IconResourceHandle("Back.gif"), "Previous"));
            objElements.Add(new HostedToolBarButton("Find", new IconResourceHandle("Search.gif"), "Find"));
            objElements.Add(new HostedToolBarButton("Next", new IconResourceHandle("Next.gif"), "Next"));
            objElements.Add(new HostedToolBarSeperator());
            if (IsPermis(idAddNew))
                objElements.Add(new HostedToolBarButton("Add New", new IconResourceHandle("Add.png"), "C"));
            if (IsPermis(idEdit))
                objElements.Add(new HostedToolBarButton("Edit", new IconResourceHandle("Edit.png"), "A"));
            if (IsPermis(idAddNew))
                objElements.Add(new HostedToolBarButton("Copy", new IconResourceHandle("Copy.png"), "O"));
            if (IsPermis(idDelete))
                objElements.Add(new HostedToolBarButton("Delete", new IconResourceHandle("Delete.png"), "X"));
            objElements.Add(new HostedToolBarSeperator());
            if (IsPermis(idTransferIn))
                objElements.Add(new HostedToolBarButton("clsTransfer In", new IconResourceHandle("Down.png"), "TI"));
            if (IsPermis(idImportData))
                objElements.Add(new HostedToolBarButton("Import Data", new IconResourceHandle("Import.ico"), "IM"));
            if (IsPermis(idTransferOut))
                objElements.Add(new HostedToolBarButton("clsTransfer Out", new IconResourceHandle("Up.png"), "TO"));
            objElements.Add(new HostedToolBarSeperator());
            if (IsPermis(idConfig))
                objElements.Add(new HostedToolBarButton("Config", new IconResourceHandle("Config.png"), "Config"));

            
            objElements.Add(new HostedToolBarSeperator());
            if (IsPermis(idPrint))
                objElements.Add(new HostedToolBarButton("Print", new IconResourceHandle("Print.png"), "P"));
            objElements.Add(new HostedToolBarButton("Refresh", new IconResourceHandle("Refresh.png"), "R"));
            return (HostedToolBarElement[])objElements.ToArray(typeof(HostedToolBarElement));
        }

        public void OnToolBarButtonClick(HostedToolBarButton objButton, EventArgs objEvent)
        {
            try
            {
                frmGadgetConfig frm = new frmGadgetConfig(GetMainForm());
                sErr = "";
                string strAction = (string)objButton.Tag;

                switch (strAction)
                {
                    case "C":
                        DTO.LIST_GADGETInfo inf = new DTO.LIST_GADGETInfo() { Owner = GetMainForm().PODInfo.USER_ID };
                        mygadget.Info = inf;
                        frm = new frmGadgetConfig(mygadget, GetMainForm());
                        frm.FormClosed += delegate(object form, FormClosedEventArgs args)
                        {
                            if (((frmGadgetConfig)form).DialogResult == DialogResult.OK)
                            {
                                mygadget = ((frmGadgetConfig)form).Gadget;
                                UpdateRecord(mygadget.Info);
                                LoadDB("");
                                ThrowMsg(mygadget.sErr);
                            }
                        };
                        frm.ShowDialog();
                        break;
                    case "A":
                        frm = new frmGadgetConfig(mygadget, GetMainForm());
                        frm.FormClosed += (form, args) =>
                        {
                            if (((frmGadgetConfig)form).DialogResult == DialogResult.OK)
                            {
                                mygadget = ((frmGadgetConfig)form).Gadget;
                                UpdateRecord(mygadget.Info);
                                LoadDB("");
                                ThrowMsg(mygadget.sErr);
                            }
                        };
                        frm.ShowDialog();
                        break;
                  
                    case "Config":
                        frmDashboardConfig frmdbconfig = new frmDashboardConfig(GetMainForm());
                        frmdbconfig.FormClosed += (form, args) =>
                        {
                            if (((frmDashboardConfig)form).DialogResult == DialogResult.OK)
                            {
                                string strparams = InitParam("");
                                LoadDB("");
                                ThrowMsg(mygadget.sErr);
                            }
                        };
                        frmdbconfig.ShowDialog();


                        break;
                    case "O":
                        mygadget.Info.ID = -1;
                        frm = new frmGadgetConfig(mygadget, GetMainForm());
                        frm.FormClosed += (form, args) =>
                        {
                            if (((frmGadgetConfig)form).DialogResult == DialogResult.OK)
                            {
                                mygadget = ((frmGadgetConfig)form).Gadget;
                                UpdateRecord(mygadget.Info);
                                LoadDB("");
                                ThrowMsg(mygadget.sErr);
                            }
                        };
                        frm.ShowDialog();
                        break;
                    case "Next":
                        _iCurrent++;
                        LoadPosition(ref _iCurrent);


                        break;
                    case "Find":
                        Forms.frmView frmView = new Forms.frmView("DDB", GetMainForm());

                        frmView.FormClosed += (form, args) =>
                        {
                            if (((Forms.frmView)form).DialogResult == DialogResult.OK)
                            {
                                DTO.LIST_GADGETInfo infGadgte = new DTO.LIST_GADGETInfo(((Forms.frmView)form).ReturnValue);
                                DataTable dt = GetMainForm().GetTable(_strType);
                                _iCurrent = dt.Rows.IndexOf(((Forms.frmView)form).ReturnValue);
                                mygadget.Info = infGadgte;
                                mygadget.Reload();
                                LoadDB("");
                                ThrowMsg(mygadget.sErr);
                            }
                        };
                        frmView.ShowDialog();


                        break;
                    case "Previous":
                        _iCurrent--;
                        LoadPosition(ref _iCurrent);
                        break;
                    case "X":
                        Delete();

                        break;
                    case "TI":
                        Forms.frmTransferIn frmTI = new Forms.frmTransferIn(_strType, GetMainForm());

                        frmTI.ShowDialog();

                        break;
                    case "TO":
                        Forms.frmTransferOut frmTO = new Forms.frmTransferOut(_strType, GetMainForm());
                        frmTO.Show();
                        break;
                    case "R":
                        RefreshList();
                        break;
                    case "IM":
                        ImportData();
                        break;
                    case "P":
                        if (mygadget.Info.ID != -1)
                        {
                            ExcelFile file = mygadget.PrintExcel();
                            MemoryStream ms = new MemoryStream();

                            file.Save(ms);
                            DownloadGateway myDownload = new DownloadGateway(ms, _strType + ".xls");

                            myDownload.ContentType = "application/vnd.ms-excel";
                            myDownload.StartDownload(this);
                        }
                        break;
                }
                _processStatus = strAction;
                if (sErr == "")
                    ThrowMsg("Command: " + _processStatus);
            }
            catch (Exception ex)
            {
                ThrowMsg(ex.Message + Environment.NewLine + ex.Source);
            }
        }

        private void ImportData()
        {
            //frmImport imp = new frmImport(MainForm.DB,MainForm);
            //imp.Show();
        }

        private void LoadPosition(ref int _iCurrent)
        {
            if (mygadget == null)
            {
                if (_iCurrent == -1)
                    _iCurrent = 0;
                if (!GetMainForm().IsContainsTables(_strType))
                    GetMainForm().LoadDataTable(_strType);
                DataTable dt = GetMainForm().GetTable(_strType);
                if (_iCurrent >= dt.Rows.Count)
                {
                    _iCurrent = dt.Rows.Count - 1;
                }
                if (dt.Rows.Count > 0)
                {
                    DTO.LIST_GADGETInfo infGadgte = new DTO.LIST_GADGETInfo(dt.Rows[_iCurrent]);
                    mygadget.Info = infGadgte;
                    mygadget.Reload();
                    LoadDB("");
                    ThrowMsg(mygadget.sErr);
                }
                else
                {
                    myHtmlbox1.Url = "";
                }
            }
        }

        private void LoadDB(string args)
        {
            string strparams = InitParam(args);
            mygadget.SetParameters(strparams);
            //_xls = mygadget.Xls;
            //string filename = "";
            mygadget.Path = String.Format("{0}Documents\\Report\\{1}\\", MainForm.ServerPath, GetMainForm().PODInfo.USER_ID);
            myHtmlbox1.Html = mygadget.LoadGadgetToString(myHtmlbox1.Handle.ToString());
            // myHtmlbox1.Url = mygadget.LoadGadget(ref filename, "Documents/Report/" + GetMainForm().PODInfo.USER_ID, myHtmlbox1.Handle.ToString());
            if (myHtmlbox1.Html == "")
                myHtmlbox1.Url = "/ReportTemplate/DB_ERROPAGE.htm";
            myHtmlbox1.Update();
            SetTitle(mygadget.Info.Description);
            ThrowMsg(mygadget.sErr);
        }
        private string InitParam(string args)
        {
            if (GetMainForm().FormPara.Rows.Count == 0)
                GetMainForm().FormPara.Rows.Add(GetMainForm().FormPara.NewRow());
            if (GetMainForm().FormPara.Rows.Count == 1 && (GetMainForm().FormPara.Rows[0]["P3"] == DBNull.Value || GetMainForm().FormPara.Rows[0]["P3"].ToString() == ""))
                GetMainForm().FormPara.Rows[0]["P3"] = DateTime.Now.Year * 1000 + DateTime.Today.Month;
            if (args != "")
            {
                string[] arr = args.Split('&');
                if (arr != null && arr.Length > 0)
                {
                    foreach (string tmp in arr)
                    {
                        string[] value = tmp.Split('=');
                        if (value.Length >= 2)
                            if (GetMainForm().FormPara.Columns.Contains(value[0]))
                            {
                                GetMainForm().FormPara.Rows[0][value[0]] = tmp.Substring(value[0].Length + 1);
                                args = args.Replace(tmp + "&", "").Replace(tmp, "");
                            }
                    }
                }
            }
            foreach (DataColumn x in GetMainForm().FormPara.Columns)
            {
                args += String.Format("&{0}={1}", x.ColumnName, GetMainForm().FormPara.Rows[0][x]);
            }
            string result = String.Format("OperatorID={0}&EmployeeID={1}", GetMainForm().PODInfo.USER_ID, GetMainForm().PODInfo.EMP_ID);

            foreach (DataColumn col in GetMainForm().FormPara.Columns)
            {
                //if (GetMainForm().FormPara.Rows[0][col].ToString() != "")
                result += String.Format("&{0}={1}", col.ColumnName, GetMainForm().FormPara.Rows[0][col]);
            }
            result += "&" + args;
            return result;
        }

        private void RefreshList()
        {
            mygadget.Xls = null;
            mygadget.XlsPrint = null;
            LoadDB("");
        }

        private void Delete()
        {
            BUS.LIST_GADGETControl ctr = new BUS.LIST_GADGETControl();
            BUS.LIST_CHARTControl chartctr = new BUS.LIST_CHARTControl();

            if (mygadget.ID != -1)
            {
                ctr.Delete(GetMainForm().DB, mygadget.ID);
                chartctr.Delete_byGadget(GetMainForm().DB, mygadget.ID);
                GetMainForm().RemoveRecord(_strType, DTO.LIST_GADGETInfo.Field.ID.ToString(), mygadget.Info.ID.ToString());
                LoadPosition(ref _iCurrent);
            }
        }


        private void UpdateRecord(DTO.LIST_GADGETInfo info)
        {
            GetMainForm().GetTable(_strType).BeginLoadData();
            GetMainForm().UpdateRecord(_strType, info.ToDataRow(GetMainForm().GetTable(_strType)).ItemArray, LoadOption.OverwriteChanges);
            GetMainForm().GetTable(_strType).EndLoadData();
            Rebind();
        }
        private static void Rebind()
        {
            //bisTER.DataSource =  GetMainForm().GetTable(_strType);
        }
        private void ThrowMsg(string sErr)
        {
            BaseForm x = Parent.Parent as BaseForm;
            if (x != null)
            {
                x.SetMsg(sErr);
            }
        }



        #endregion

        private void DDB_Load(object sender, EventArgs e)
        {
            BUS.POGControl ctrpog = new BUS.POGControl();
            DTO.POGInfo pogInf = ctrpog.Get(GetMainForm().PODInfo.ROLE_ID, ref sErr);
            if (!GetMainForm().IsContainsTables(_strType))
                GetMainForm().LoadDataTable(_strType);
            DataTable dt = GetMainForm().GetTable(_strType);

            DataRow[] rows = null;
            if (pogInf.RPT_CODE == "")
                rows = dt.Select("IsDefault='True'");
            else
            {
                rows = dt.Select(String.Format("{0}='{1}'", DTO.LIST_GADGETInfo.Field.ID, pogInf.RPT_CODE));
            }
            DTO.LIST_GADGETInfo inf = new DTO.LIST_GADGETInfo() { Owner = GetMainForm().PODInfo.USER_ID };
            if (rows == null || rows.Length == 0)
            {
                if (dt.Rows.Count > 0)
                    inf = new DTO.LIST_GADGETInfo(dt.Rows[0]);
            }
            else
            {
                inf = new DTO.LIST_GADGETInfo(rows[0]);
                _iCurrent = dt.Rows.IndexOf(rows[0]);
            }
            mygadget = new MyGadget(inf, "", GetMainForm());
            mygadget.Reload();
            LoadDB("");
            ThrowMsg(mygadget.sErr);

        }
        public string GetLanguage()
        {
            return language;
        }

    }
}